package com.dp.quickStart;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dp.entity.Item;
import com.dp.entity.ItemDoc;
import com.dp.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: dupeng
 * @CreateTime: 2024-12-18  11:36
 * @Description: TODO
 */
@SpringBootTest
@Slf4j
public class Demo1 {

    private RestHighLevelClient client;
    @Autowired
    private ItemService itemService;

    @BeforeEach
    public void before() {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://152.136.59.90:9200")
        ));
    }


    @Test
    public void test() throws IOException {
        //创建一个索引（table）
        CreateIndexRequest request = new CreateIndexRequest("item");
        //向request中添加mapping信息（表结构）
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        //执行创建索引
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @Test
    public void createDom() throws IOException {
        //创建一个索引（table）
        IndexRequest request = new IndexRequest("item").id("2");
        //向request中添加mapping信息（表结构）
        request.source("{\"brand\": \"我是一个超人2\"}", XContentType.JSON);
        //执行创建索引
        client.index(request, RequestOptions.DEFAULT);
    }

    @Test
    public void syncItemToEs() throws IOException {
        // 分页查询商品数据
        int pageNo = 1;
        int size = 1000;
        while (true) {
            Page<Item> page = itemService.lambdaQuery().eq(Item::getStatus, 1).page(new Page<Item>(pageNo, size));
            // 非空校验
            List<Item> items = page.getRecords();
            if (CollectionUtils.isEmpty(items)) {
                return;
            }
            log.info("加载第{}页数据，共{}条", pageNo, items.size());
            // 1.创建Request
            BulkRequest request = new BulkRequest("items");
            // 2.准备参数，添加多个新增的Request
            for (Item item : items) {
                // 2.1.转换为文档类型ItemDTO
                ItemDoc itemDoc = new ItemDoc();
                BeanUtils.copyProperties(item, itemDoc);
                // 2.2.创建新增文档的Request对象
                request.add(new IndexRequest()
                        .id(item.getId().toString())
                        .source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON));
            }
            // 3.发送请求
            client.bulk(request, RequestOptions.DEFAULT);

            // 翻页
            pageNo++;
        }
    }

    @AfterEach
    public void after() throws IOException {
        client.close();
    }


    static final String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"stock\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"image\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"category\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"sold\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"commentCount\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"isAD\":{\n" +
            "        \"type\": \"boolean\"\n" +
            "      },\n" +
            "      \"updateTime\":{\n" +
            "        \"type\": \"date\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";


    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        List<Integer> list2 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

        // 获取 list1 中不在 list2 中的元素
        List<Integer> result = new ArrayList<>(list1);
        result.removeAll(list2);

        // 输出结果
        System.out.println("List1 不在 List2 中的元素：" + result);
    }
}
